﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.CacheManageConverter;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.LocalDatabase;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheManage
{
    public partial class QueuePage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false, IsRefreshUI = true;
        private int comicId = 0, bookId = 0;
        //private CacheQueueAssistant CQA;

        public QueuePage()
        {
            InitializeComponent();
            //
            if (App.CQASingleton.GetIsRunning() || App.CQASingleton.GetIsLoadNetData())
            {
                //已经在运行，不需要重启
                LogHelper.LogInfo("已经在运行，不需要重启", this.GetType(), MethodBase.GetCurrentMethod());
                return;
            }
            else
            {
                App.CQASingleton.InitCacheQueueAssistant().OnCacheQueueAssistantStatusChanged += CQA_OnCacheQueueAssistantStatusChanged;
                App.CQASingleton.InitCacheQueueAssistant().InitCacheQueue(this.comicId, this.bookId);
            }
            //
            IsNeedReloadData = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            IsRefreshUI = true;
            //
            string tmpComicId, tmpBookId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            base.NavigationContext.QueryString.TryGetValue("bookId", out tmpBookId);
            int.TryParse(tmpBookId, out bookId);
            if (comicId <= 0 || bookId <= 0)
            {
                if (base.NavigationService.CanGoBack)
                {
                    base.NavigationService.GoBack();
                }
                return;
            }


            //加载下载过的漫画列表
            if (this.IsNeedReloadData)
            {
                LoadComicChapters();
                //
                //CacheQueueTransfer(1);
                //WaitCallback callback = new WaitCallback(CacheQueueTransfer);
                //ThreadPool.QueueUserWorkItem(callback);
                //
                //if (CQA == null)
                //{
                //    CQA = App.CQASingleton.InitCacheQueueAssistant();
                //}
                //CQA.OnCacheQueueAssistantStatusChanged += CQA_OnCacheQueueAssistantStatusChanged;
                //CQA.InitCacheQueue(this.comicId, this.bookId);
            }

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //if (CQA != null)
            //{
            //    CQA.OnCacheQueueAssistantStatusChanged -= CQA_OnCacheQueueAssistantStatusChanged;
            //}
            App.CQASingleton.InitCacheQueueAssistant().OnCacheQueueAssistantStatusChanged -= CQA_OnCacheQueueAssistantStatusChanged;
            IsRefreshUI = false;
            base.OnNavigatedFrom(e);
        }


        private void CQA_OnCacheQueueAssistantStatusChanged(LDBComicChapterImage ldbComicChapterImage)
        {
            this.Dispatcher.BeginInvoke(() =>
          {
              //更新对应章节的状态
              if (ldbComicChapterImage == null)
                  return;

              LogHelper.LogInfo(ldbComicChapterImage.ComicIdAndBookIdAndPartId + "\t" + ldbComicChapterImage.ImageUrl, this.GetType(), MethodBase.GetCurrentMethod());

              var grids = Helper.FindChildren<Grid>(this.lstAllChapter);
              if (!(grids != null && grids.Count() > 0))
                  return;
              foreach (Grid grid in grids)
              {
                  if (grid == null)
                      continue;

                  LDBComicChapter dbChapter = grid.DataContext as LDBComicChapter;
                  if (dbChapter == null)
                      continue;
                  if (!dbChapter.ComicIdAndBookIdAndPartId.Equals(ldbComicChapterImage.ComicIdAndBookIdAndPartId))
                      continue;
                  if (!(grid != null && grid.Children != null && grid.Children.Count > 0))
                      continue;
                  //
                  if (IsRefreshUI)
                  {
                      UpdateGrid(grid, dbChapter);
                  }
              }
          });
        }

        #region ********************更新下载状态信息******************************
        void UpdateGrid(Grid grid, LDBComicChapter dbChapter)
        {
            if (string.IsNullOrWhiteSpace(dbChapter.ComicIdAndBookIdAndPartId))
            {
                return;
            }
            ObservableCollection<LDBComicChapterImage> items = new ObservableCollection<LDBComicChapterImage>();

            var cpIds = new ParseComicBookPartIds();
            cpIds.ParseCBPId(dbChapter.ComicIdAndBookIdAndPartId);
            if (!(cpIds.BookId > 0 && cpIds.ComicId > 0 && cpIds.PartId > 0))
            {
                return;
            }

            items = App.dbContextHelper.GetAllComicChapterImageByComicIdAndChapterId(cpIds.ComicId, cpIds.BookId, cpIds.PartId);

            //
            foreach (UIElement element in grid.Children)
            {
                if (element == null)
                    continue;


                if (element is ProgressBar)
                {
                    var el = element as ProgressBar;
                    if (el == null)
                        continue;
                    el.Value = GetDonwloadStatusProgress(items);
                }
                else if (element is StackPanel)
                {
                    var el = element as StackPanel;
                    if (!(el != null && el.Children != null && el.Children.Count > 0))
                        continue;
                    foreach (UIElement sp in el.Children)
                    {
                        if (sp == null)
                            continue;
                        var txt = sp as TextBlock;
                        if (txt == null)
                            continue;
                        if (txt.Name.Equals("txtCurrentTotal"))
                        {
                            txt.Text = GetDownloadCurrentImages(items).ToString();
                        }
                        else if (txt.Name.Equals("txtTotalCount"))
                        {
                            txt.Text = ((items != null && items.Count > 0) ? items.Count : 0).ToString();
                        }
                        else if (txt.Name.Equals("txtStatusInfo"))
                        {
                            txt.Text = GetDownloadStatusInfo(items);
                        }
                    }
                }
                else if (element is HyperlinkButton)
                {
                    var el = element as HyperlinkButton;
                    if (el == null)
                        continue;
                    string statusInfo = GetDownloadStatusInfo(items);
                    if (ContentDownloadStatus.已完成.ToString().Equals(statusInfo))
                    {
                        el.Content = ContentDownloadOperation.阅读.ToString();
                    }
                    else if (ContentDownloadStatus.已暂停.ToString().Equals(statusInfo))
                    {
                        el.Content = ContentDownloadOperation.下载.ToString();
                    }
                    else if (ContentDownloadStatus.下载中.ToString().Equals(statusInfo))
                    {
                        el.Content = ContentDownloadOperation.暂停.ToString();
                    }
                    else if (ContentDownloadStatus.等待中.ToString().Equals(statusInfo))
                    {
                        el.Content = ContentDownloadOperation.删除.ToString();
                    }
                }
            }
        }


        private double GetDonwloadStatusProgress(ObservableCollection<LDBComicChapterImage> items)
        {
            double result = 0.00;
            try
            {
                if (items != null && items.Count > 0)
                {
                    int totalCompleted = items.Where<LDBComicChapterImage>(p => ContentDownloadStatus.已完成.ToString().Equals(p.DownloadStatus)).Count();
                    result = ((totalCompleted * 1.00) / (items.Count * 1.00)) * 100.00;
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
            }
            LogHelper.LogInfo("progress:\t" + result, this.GetType(), MethodBase.GetCurrentMethod());
            return result;
        }

        private string GetDownloadStatusInfo(ObservableCollection<LDBComicChapterImage> items)
        {
            string result = ContentDownloadStatus.等待中.ToString();

            if (items != null && items.Count > 0)
            {
                int completedTotal = items.Where(p => ContentDownloadStatus.已完成.ToString().Equals(p.DownloadStatus)).Count();
                if (items.Count == completedTotal)
                    result = ContentDownloadStatus.已完成.ToString();
                else
                    result = ContentDownloadStatus.下载中.ToString();
            }
            return result;
        }

        private int GetDownloadCurrentImages(ObservableCollection<LDBComicChapterImage> items)
        {
            int total = 0;
            if (items != null && items.Count > 0)
            {
                total = items.Where(p => ContentDownloadStatus.已完成.ToString().Equals(p.DownloadStatus)).Count();
            }
            return total;
        }
        #endregion ********************更新下载状态信息******************************

        /// <summary>
        /// 加载缓存下载队列
        /// </summary>
        /// <param name="isStartCacheQueue">true:重启缓存下载队列</param>
        void LoadComicChapters(bool isStartCacheQueue = false)
        {
            var localCacheItems = App.dbContextHelper.GetAllChaptersByComicId(this.comicId, this.bookId);
            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }
            //全部章节
            this.lstAllChapter.ItemsSource = localCacheItems;
            this.pivotAllChapter.Header = string.Format("全部({0})", this.lstAllChapter.ItemsSource != null ? this.lstAllChapter.Items.Count.ToString() : "0");
            //已完成的章节
            var itemsFinished = (from p in localCacheItems where p.DownloadStatus.Equals(ContentDownloadStatus.已完成.ToString()) select p).OrderBy(p => p.PartId).ToList<LDBComicChapter>();
            if (itemsFinished != null && itemsFinished.Count > 0)
            {
                var ocItemsFinished = new ObservableCollection<LDBComicChapter>(itemsFinished);
                this.lstFinishedChapter.ItemsSource = ocItemsFinished;
            }
            this.pivotFinishedChapter.Header = string.Format("已完成({0})", this.lstFinishedChapter.ItemsSource != null ? this.lstFinishedChapter.Items.Count.ToString() : "0");
            //重启缓存下载队列
            if (isStartCacheQueue)
            {
                //CQA = App.CQASingleton.InitCacheQueueAssistant();
                //CQA.IsRuning = false;
                //CQA.IsLoadNetData = false;
                //CQA.InitCacheQueue(this.comicId, this.bookId);
                //

                if (App.CQASingleton.GetIsRunning() || App.CQASingleton.GetIsLoadNetData())
                {
                    //已经在运行，不需要重启
                    LogHelper.LogInfo("已经在运行，不需要重启", this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }
                else
                {
                    App.CQASingleton.InitCacheQueueAssistant().OnCacheQueueAssistantStatusChanged += CQA_OnCacheQueueAssistantStatusChanged;
                    //App.CQASingleton.InitCacheQueueAssistant().IsRuning = false;
                    //App.CQASingleton.InitCacheQueueAssistant().IsLoadNetData = false;
                    App.CQASingleton.SetIsRunning(false);
                    App.CQASingleton.SetIsLoadNetData(false);
                    App.CQASingleton.InitCacheQueueAssistant().InitCacheQueue(this.comicId, this.bookId);
                }
            }
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.pivotFinishedChapter == this.pivot.SelectedItem)
            {
                ApplicationBar = (ApplicationBar)Resources["appbarPivotFinished"];
            }
            else if (this.pivotAllChapter == this.pivot.SelectedItem)
            {
                ApplicationBar = (ApplicationBar)Resources["appbarPivotAll"];
            }
        }


        #region 正在下载
        private void appBarCheck_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择全部".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.lstAllChapter.SelectAll();
                }
                else
                {
                    appBarIcon.Text = "选择全部";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.lstAllChapter.SelectedItems.Clear();
                }
            });
        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            if (this.lstAllChapter.SelectedItems.Count <= 0)
            {
                MessageToastManager.Show("请选择要删除的漫画！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认删除选中的 {0} 漫画章节？", this.lstAllChapter.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            var sources = this.lstAllChapter.ItemsSource as ObservableCollection<LDBComicChapter>;
            if (!(sources != null && sources.Count > 0))
                return;

            while (this.lstAllChapter.SelectedItems.Count > 0)
            {
                var item = this.lstAllChapter.SelectedItems[0] as LDBComicChapter;
                if (item == null)
                    continue;

                try
                {
                    //删除漫画中的章节、漫画中章节的图片，如果漫画章节为空了则要把漫画也要删除（同时书架信息也要删除）
                    bool result = App.dbContextHelper.RemoveComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                    if (result)
                    {
                        App.dbContextHelper.RemoveComicChapterImageByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                        this.lstAllChapter.SelectedItems.Remove(item);
                        sources.Remove(item);
                    }
                    //App.dbContextHelper.RemoveComicChapterImageByComicId(item.ComicId);
                    //App.dbContextHelper.RemoveComicChapterByComicId(item.ComicId);
                    //App.dbContextHelper.RemoveComicByComicId(item.ComicId);                    
                    //删除数据库信息后，书架也需要删除
                    //LocalUserBookStoreAlbumHelper helper = new LocalUserBookStoreAlbumHelper();
                    //helper.RemoveComicFromLocalUserBookStoreAlbum(item.ComicId);
                    //
                }
                catch (Exception err)
                {
                    LogHelper.LogInfo(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }

        /// <summary>
        /// 暂停下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void appBarPause_Click(object sender, EventArgs e)
        {
            if (this.lstAllChapter.SelectedItems.Count <= 0)
            {
                MessageToastManager.Show("请选择要 暂停下载 的漫画章节！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认将选中的 {0} 漫画章节 暂停下载？", this.lstAllChapter.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            var sources = this.lstAllChapter.ItemsSource as ObservableCollection<LDBComicChapter>;
            if (!(sources != null && sources.Count > 0))
                return;

            while (this.lstAllChapter.SelectedItems.Count > 0)
            {
                var item = this.lstAllChapter.SelectedItems[0] as LDBComicChapter;
                if (item == null)
                    continue;
                this.lstAllChapter.SelectedItems.Remove(item);
                if (ContentDownloadStatus.下载中.Equals(item.DownloadStatus)
                    || ContentDownloadStatus.已完成.Equals(item.DownloadStatus)
                    || ContentDownloadStatus.已暂停.Equals(item.DownloadStatus))
                    continue;
                try
                {
                    bool result = App.dbContextHelper.PauseComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                }
                catch
                {
                }
            }

            this.LoadComicChapters();
        }

        private void appBarDownload_Click(object sender, EventArgs e)
        {
            //TODO 将选中的章节标识为下载（等待下载状态）
            if (this.lstAllChapter.SelectedItems.Count <= 0)
            {
                MessageToastManager.Show("请选择要 下载 的漫画章节！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认将选中的 {0} 漫画章节进行下载？", this.lstAllChapter.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            if (this.lstAllChapter.SelectedItems != null && this.lstAllChapter.SelectedItems.Count > 0)
            {
                for (int i = 0; i < this.lstAllChapter.SelectedItems.Count; i++)
                {
                    var item = this.lstAllChapter.SelectedItems[i] as LDBComicChapter;
                    if (item == null)
                    {
                        continue;
                    }
                    //
                    if (ContentDownloadStatus.已暂停.ToString().Equals(item.DownloadStatus))
                    {
                        bool result = App.dbContextHelper.PendingComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                    }
                }
                //
                //this.lstAllChapter.SelectedItems.Clear();
                this.LoadComicChapters(true);
            }
        }

        private void lbtnOperation_Click(object sender, RoutedEventArgs e)
        {
            var lbtn = sender as HyperlinkButton;
            if (lbtn == null)
                return;
            LDBComicChapter item = lbtn.DataContext as LDBComicChapter;
            if (item == null)
                return;
            string operationMethod = lbtn.Content != null ? Convert.ToString(lbtn.Content) : string.Empty;
            if (string.IsNullOrWhiteSpace(operationMethod))
                return;
            if (ContentDownloadOperation.暂停.ToString().Equals(operationMethod))
            {
                //将当前章节设置为暂停
                bool result = App.dbContextHelper.PauseComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                if (result)
                {
                    this.LoadComicChapters();
                }
            }
            else if (ContentDownloadOperation.下载.ToString().Equals(operationMethod))
            {
                //将当前章节设置为立即下载
                bool result = App.dbContextHelper.PendingComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                if (result)
                {
                    this.LoadComicChapters(true);
                }
            }
            else if (ContentDownloadOperation.删除.ToString().Equals(operationMethod))
            {
                bool result = App.dbContextHelper.RemoveComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
                if (result)
                {
                    if (this.lstAllChapter.SelectedItems != null && this.lstAllChapter.SelectedItems.Count > 0)
                    {
                        this.lstAllChapter.SelectedItems.Remove(item);
                    }
                    var sources = this.lstAllChapter.ItemsSource as ObservableCollection<LDBComicChapter>;
                    if (sources != null && sources.Count > 0)
                    {
                        sources.Remove(item);
                    }
                }
                //CacheQueueHelper.Instance().CacheQueueHandler(this.comicId);
            }
            else if (ContentDownloadOperation.阅读.ToString().Equals(operationMethod))
            {
                NaviService.Navigate(ComicIslandPage.RCComicReaderPage, string.Concat("?comicId=", item.ComicId, "&bookId=", item.BookId, "&comicPartId=", item.PartId));
            }

        }
        #endregion ******************************正在下载******************************

        #region ******************************已完成******************************
        private void appbarFinishedCheckAll_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择全部".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.lstFinishedChapter.SelectAll();
                }
                else
                {
                    appBarIcon.Text = "选择全部";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.lstFinishedChapter.SelectedItems.Clear();
                }
            });
        }

        private void appbarFinishedDelete_Click(object sender, EventArgs e)
        {
            if (this.lstFinishedChapter.SelectedItems.Count <= 0)
            {
                MessageToastManager.Show("请选择要删除的漫画！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认删除选中的 {0} 漫画章节？", this.lstFinishedChapter.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            var sources = this.lstFinishedChapter.ItemsSource as ObservableCollection<LDBComicChapter>;
            if (!(sources != null && sources.Count > 0))
                return;

            while (this.lstFinishedChapter.SelectedItems.Count > 0)
            {
                var item = this.lstFinishedChapter.SelectedItems[0] as LDBComicChapter;
                if (item == null)
                    continue;

                try
                {
                    //删除漫画中的章节、                                      
                    if (App.dbContextHelper.RemoveComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId))
                    {
                        this.lstFinishedChapter.SelectedItems.Remove(item);
                        //TODO 漫画中章节的图片是否删除,如果漫画章节为空了则要把漫画也要删除（同时书架信息也要删除）  
                        //App.dbContextHelper.RemoveComicByComicId(item.ComicId);                                        
                        //LocalUserBookStoreAlbumHelper helper = new LocalUserBookStoreAlbumHelper();
                        //helper.RemoveComicFromLocalUserBookStoreAlbum(item.ComicId);
                        //
                        sources.Remove(item);
                    }

                }
                catch (Exception err)
                {
                    LogHelper.LogInfo(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }

        private void lbtnFinishedRead_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var lbtn = sender as HyperlinkButton;
            if (lbtn == null)
                return;
            LDBComicChapter item = lbtn.DataContext as LDBComicChapter;
            if (item == null)
                return;

            NaviService.Navigate(ComicIslandPage.RCComicReaderPage, string.Concat("?comicId=", item.ComicId, "&bookId=", item.BookId, "&comicPartId=", item.PartId));
        }

        private void lbtnFinishedDeleted_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var lbtn = sender as HyperlinkButton;
            if (lbtn == null)
                return;
            LDBComicChapter item = lbtn.DataContext as LDBComicChapter;
            if (item == null)
                return;

            bool result = App.dbContextHelper.RemoveComicChapterByComicIdAndChapterId(item.ComicId, item.BookId, item.PartId);
            if (result)
            {
                if (this.lstFinishedChapter.SelectedItems != null && this.lstFinishedChapter.SelectedItems.Count > 0)
                {
                    this.lstFinishedChapter.SelectedItems.Remove(item);
                }
                var sources = this.lstFinishedChapter.ItemsSource as ObservableCollection<LDBComicChapter>;
                if (sources != null && sources.Count > 0)
                {
                    sources.Remove(item);
                }
            }
        }
        #endregion ******************************已完成******************************






    }
}